//
//  Status.swift
//  波波微博
//
//  Created by wave on 15/8/1.
//  Copyright © 2015年 wave. All rights reserved.
//

import UIKit
import SDWebImage

class Status: NSObject {

    //微博创建时间
    var created_at:String?
    //每一个微博都有一个自己的id,可以保证每条微博都在服务器上有一个独立的记录,理论上每次发一条微博id就会+1
    var id:Int = 0
    //微博的信息内容
    var text:String?
    //微博来源
    var source:String?
    //配图数组
    var pic_urls: [[String: AnyObject]]?{
        didSet{
        /*
            1.判断数组中是否有数据
            2.实例化数组,pictureURLs
            3.遍历字典,生成URL的数组
        */
            if pic_urls?.count == 0{
                return
            }
            
            //实例化数组
            storedPictureURLs = [NSURL]()
            storedLargePictureURLs = [NSURL]()
            
            for dict in pic_urls!{
                
                if let urlString = dict["thumbnail_pic"] as? String{
                    //生成缩略图的url
                    storedPictureURLs?.append(NSURL(string: urlString)!)
                    
                    //大图的URL
                    let largeURL = urlString.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
//                    print(largeURL)
                    storedLargePictureURLs?.append(NSURL(string: largeURL)!)
                }
            }
//            print("---")
        }
    }
    //'保存'配图的URL的数组
    private var storedPictureURLs:[NSURL]?
    //'保存'配图的大图URL数组
    private var storedLargePictureURLs: [NSURL]?
    //配图的URL的数组属性
    var pictureURLs: [NSURL]?{
    
        return retweeted_status == nil ? storedPictureURLs : retweeted_status?.storedPictureURLs
    }
    //返回大图的URL数组
    var largePicktureURLs:[NSURL]?{
        
        return retweeted_status == nil ? storedLargePictureURLs : retweeted_status?.storedLargePictureURLs
    }
    //用户属性
    var user:User?
    //行高属性
    var rowHeigth: CGFloat?
    //转发微博
    var retweeted_status: Status?
    
    //构造函数,从服务器返回一个字典
    init(dict:[String:AnyObject]){
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    //必须要重写这个方法
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    //KVC并赋值不到user里去,所以重写KVC的方法进行判断赋值
    override func setValue(value: AnyObject?, forKey key: String) {

        //判断key是否是user,如果是user单独处理
        if key == "user"{
            
            //判断value是否是一个有效的字典
            if let dict = value as? [String:AnyObject]{
            
                //创建用户数据
                user = User(dict: dict)
            }
            
            return
        }
        super.setValue(value, forKey: key)
        
        if key == "retweeted_status"{
            
            if let dict = value as? [String : AnyObject]{
            
                retweeted_status = Status(dict: dict)
            }
            return
        }
    }
    
    
    //写一个类函数,用来加载微博数据
    class func loadStatus(since_id:Int,max_id:Int,finished:(dataList:[Status]?,error:NSError?) -> ()){
    
        NetworkTools.sharedTools.loadStatus(since_id,max_id:max_id) { (result, error) -> () in
            
            if error != nil{
                
                finished(dataList: nil, error: error)
                return
            }
            
            //判断能否获得字典数组
            if let array = result?["statuses"] as? [[String: AnyObject]]{
            
                //遍历数组,字典转模型
                var list = [Status]()
                
                for dict in array{
                    
                    list.append(Status(dict: dict))
                }
                
                self.cacheWebImage(list, finished: finished)
                
                //获得完整的微博数组,可以回调
                finished(dataList: list, error: nil)
            }
            else{
                
                finished(dataList: nil, error: nil)
            }
        }
    }
    
    
    //缓存微博的网络图片
    private class func cacheWebImage(list:[Status], finished: (dataList: [Status]?, error: NSError?) -> ()){
    
        //创建调度组
        let group = dispatch_group_create()
        
        //缓存图片
        var dataLength = 0
        
        //循环遍历数组
        for status in list{
            
            //判断是否正常的url
//            print(status.pictureURLs)
            
            guard let urls = status.pictureURLs else{

                //urls为空
                continue
            }
            //遍历urls的数组.缓存图片
//            print(urls)
            for imageUrl in urls{
                
                //入组
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(imageUrl, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: {(image,_,_,_,_) in
                    
                    if image != nil{
                    
                        // print(image)
                        //将图片转换成二进制数据
                        let data = UIImagePNGRepresentation(image)!
                        dataLength += data.length
                    }
                    //出组
                    dispatch_group_leave(group)
                })
            }
        }
        
        //监听所有缓存操作的通知
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            
            print("缓存图片大小\(dataLength / 1024) K")
            print("快看我快看我,我帮你把图片缓存完了,完了!!!!!!!!")
            
            //完成回调
            finished(dataList: list, error: nil)
        }
    }
    
}


